import {Toast} from 'vant'
import apis from '../../apis'
import router from '../../router'
import store from '../../store'
import app from '../../configs/app'

export default {
    namespaced: true,

    state() {
        return {
            token: '',
            user: null,
        }
    },

    getters: {
        token: state => {
            if (!state.token) {
                state.token = localStorage.getItem('token')
            }
            return state.token
        },
        user: state => {
            return state.user
        }
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
            localStorage.token = token
        },
        SET_USER: (state, info) => {
            state.user = info
        },
    },

    actions: {
        async wxAuth(context, options) {
            let authCount = localStorage.getItem('authCount') * 1
            let code = null
            let back = null

            if (!options) {
                // do nothing
            } else if (typeof options == "string") {
                code = options
            } else {
                code = options.code
                back = options.back
            }

            let isSetToken = false
            if (!context.getters.token && code) {
                console.log("Login.")

                Toast.loading({
                    duration: 0,
                    message: '加载中...',
                });

                // Login...
                await apis.wechat.login(code).then((response) => {
                    console.log("Login...")
                    const res = response.data
                    if (res.data.token) {
                        isSetToken = true
                        console.log("SET_TOKEN")
                        context.commit('SET_TOKEN', res.data.token)
                        context.commit('SET_USER', res.data.user)
                    }
                    return res.data.user
                })

                Toast.clear();
            }

            if (isSetToken && !context.state.token) {
                throw Error('Token setting invalid')
            }

            if (!context.getters.token) {
                if (authCount > 0) {
                    return
                }
                localStorage.setItem('authCount',  authCount + 1)
                window.location.href = app.authUrl + "?back=" + encodeURIComponent(back || window.location.href)
            }
        },

        authToPage(context, pageUrl) {
            if (!context.state.user) { // no login
                store.dispatch('user/toLogin', pageUrl).then(r => {})
                return
            }
            router.push(pageUrl).then(r => {})
        },

        toLogin(context, backUrl) {
            backUrl = backUrl || app.history == 'history' ? location.pathname : location.hash.substring(1)
            localStorage.setItem('backPage', backUrl)
            router.push({name: 'wx-auth'}).then(r => {})
        },

        async getUser(context) {
            if (context.getters.user) {
                return context.getters.user
            }
            if (context.getters.token) {
                Toast.loading({
                    duration: 0,
                    message: '加载中...',
                });
                await apis.auth_user.getUser().then((response) => {
                    const res = response.data
                    context.commit('SET_USER', res.data.user)
                })
                Toast.clear();
                return context.getters.user
            }
        },

        setUser(context, user) {
            context.commit('SET_USER', user)
        },

        keepToUserInfo(context, fromName) {
            store.commit('setStatus', {key: 'return', value: true})
            store.commit('keepAlive', fromName)
            router.push({name: 'user-info'}).then(r => {})
        }
    }
}